package com.deep.deepenterpise.common;

import com.deep.deepenterpise.common.result.DrResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.function.Supplier;

/**
 * @author xyz
 * @version 1.0
 * @title DrTransactionCommon
 * @description
 * @create 2024/4/25 10:26
 */
@Service
@Slf4j
public class DrTransactionCommon {
    @Resource
    private TransactionTemplate transactionTemplate;

    /**
     * @return com.deep.deepenterpise.common.result.DrResult
     * @Auth xyz
     * @Desc //TODO 无返回值的事务操作
     * @Time 14:44 2024/6/21
     * @Param [msg, task]
     */
    public DrResult execute(String msg, Runnable task) {
        return transactionTemplate.execute(status -> {
            task.run();
            return DrResult.ok().message(msg + "成功");
        });
    }


    /**
     * @return com.deep.deepbottlecurrent.DrEntity.DrCommon.Result
     * @Auth xyz
     * @Desc //TODO 有返回值
     * @Time 08:55 2024/6/21
     * @Param [msg, supplier]
     */
    public DrResult submit(String msg, Supplier<T> supplier) {
        T data = transactionTemplate.execute(status -> supplier.get());
        return DrResult.ok().message(msg + "成功").data(data);
    }

    /**
     * @Auth xyz
     * @Desc //TODO
     * @Time 15:52 2024/5/16
     * @Param [msg, throwable]
     */
    public boolean submit(String msg, Runnable task) {
        return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
            task.run();
            return true;
        }));
    }

}
